package com.jf.car.filter;

import com.alibaba.fastjson.JSON;
import com.jf.car.bean.Userinfo;
import com.jf.car.service.UserinfoService;
import com.jf.car.service.impl.UserinfoServiceImpl;
import com.jf.car.util.MyConstants;
import com.jf.car.util.MyUtils;
import com.jf.car.util.ResultJson;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ResourceBundle;

@WebFilter("/*")
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*转换request和response*/
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /*获取请求地址*/
        String uri = request.getRequestURI();
        /*获取配置文件*/
        ResourceBundle rb = ResourceBundle.getBundle("config");
        /*获取静态资源地址*/
        /*检查请求的 URI 是否包含静态资源列表中的元素，如果是，则直接放行该请求。*/
        String[] staticList = rb.getString("filter.static.list").split(",");
        /*验证请求是否为静态资源*/
        boolean isStatic = false;
        for(int i=0;i<staticList.length;i++){
            if(uri.contains(staticList[i])){
                isStatic = true;
                break;
            }
        }
        /*放行静态资源*/
        if(isStatic){
            filterChain.doFilter(request,response);
        }else{
            /*获取Cookie，判断是否记住密码需要自动登录*/
            Cookie[] cookies =request.getCookies();
            String cv="";
            if (cookies!=null){
                for (int i=0;i<cookies.length;i++){
                    /*判断cookie中是否有“loginId”*/
                    if (cookies[i].getName().equals(MyConstants.LOGIN_COOKIE_KEY)){
                        /*cv等于cookie的value的值,也就是等于userinfo对应id的值*/
                        cv = cookies[i].getValue();
                        break;
                    }
                }
            }
            boolean isLogin = false;
            /*如果cv有值*/
            if (MyUtils.isStringNotEmpty(cv)){
                int id = Integer.parseInt(cv);
                UserinfoService userinfoService = new UserinfoServiceImpl();
                /*获取对应id的值*/
                Userinfo loginInfo = userinfoService.getById(id);
                /*如果有对应id的值,且状态码为1可用*/
                if (loginInfo!=null && loginInfo.getStatus()==1){
                    isLogin =true;
                    /*重新把用户存入session*/
                    request.getSession().setAttribute(MyConstants.LOGIN_SESSION_KEY,loginInfo);
                }
            }
            if (isLogin){
                /*如果isLogin为true则放行*/
                filterChain.doFilter(request,response);
            }else {
                /*验证请求是否为白名单*/
                String[] whiteSheet = rb.getString("filter.white.sheet").split(",");
                boolean isWhite = false;
                for(int i=0;i< whiteSheet.length;i++){
                    if(uri.endsWith(whiteSheet[i])){
                        isWhite = true;
                        break;
                    }
                }
                /*如果isWhite为true*/
                if(isWhite){
                    /*放行*/
                    filterChain.doFilter(request,response);
                }else{
                    /*获取Session*/
                    HttpSession session = request.getSession();
                    if(session.getAttribute(MyConstants.LOGIN_SESSION_KEY) != null){
                        filterChain.doFilter(request,response);
                    }else{
                        if("XMLHttpRequest".equals(request.getHeader("x-requested-with"))){
                            response.getWriter().println(JSON.toJSON(ResultJson.error(401,"登录失效，请登录！")));
                        }else{
                            String loginPath = request.getContextPath()+"/login";
                            response.setContentType("text/html;charset=utf-8");
                            response.getWriter().println("<script>top.location.replace('"+loginPath+"');</script>");
                        }
                    }
                }
            }
        }
    }

    @Override
    public void destroy() {

    }
}
